﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.XPath;

using umbraco.cms.businesslogic.media;
using System.Xml.Linq;

namespace Designit.Umb.Gallery.WebUi.usercontrols.Designit.Gallery
{
    public partial class ShowGallery : System.Web.UI.UserControl
    {
        /// <summary>
        /// Gets or sets the media folder id.
        /// </summary>
        /// <value>The folder id.</value>
        public int folderId { get; set; }

        /// <summary>
        /// Gets or sets the width of the thumb.
        /// </summary>
        /// <value>The width of the thumb.</value>
        public int ThumbWidth { get; set; }
        /// <summary>
        /// Gets or sets the height of the thumb.
        /// </summary>
        /// <value>The height of the thumb.</value>
        public int ThumbHeight { get; set; }
        /// <summary>
        /// Gets or sets the width of the image in the lightbox.
        /// </summary>
        /// <value>The width of the image in the lightbox.</value>
        public int LightBoxWidth { get; set; }
        /// <summary>
        /// Gets or sets the height of the image in the lightbox.
        /// </summary>
        /// <value>The height of the image in the lightbox.</value>
        public int LightBoxHeight { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (folderId == 0)
                return;

            umbraco.library.AddJquery();

            umbraco.library.RegisterJavaScriptFile("jquery.lightbox-0.5.min.js", "/scripts/Designit.Gallery/jquery.lightbox-0.5.min.js");
            umbraco.library.RegisterStyleSheetFile("jquery.lightbox-0.5", "/css/Designit.Gallery/jquery.lightbox-0.5.css");
            

            var sb = new StringBuilder();
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("$(document).ready(function() {");
            sb.AppendLine("  $('#diGallery a').lightBox();");
            sb.AppendLine("});");
            sb.AppendLine("</script>");
            umbraco.library.RegisterClientScriptBlock("Designit.galleryInit", sb.ToString(), false);

            //var folder = new Media(folderId);

            repImages.ItemDataBound += repImages_ItemDataBound;
            repImages.DataSource = GetGalleryItems();
            repImages.DataBind();
        }

        void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;

            var galleryItem = (GalleryItem)e.Item.DataItem;
            var hlImage = (HyperLink)e.Item.FindControl("hlImage");
            var img = (Image)e.Item.FindControl("img");
            string path = galleryItem.Path;
            hlImage.NavigateUrl = GetImageUrl(path, false);
            hlImage.ToolTip = galleryItem.Name;
            img.ImageUrl = GetImageUrl(path, true);
            img.AlternateText = galleryItem.Name;
        }

        private string GetImageUrl(string imagePath, bool thumb)
        {
            int width = LightBoxWidth;
            int height = LightBoxHeight;
            if (thumb)
            {
                width = ThumbWidth;
                height = ThumbHeight;
            }
            return string.Format("/umbraco/ImageGen.ashx?image={0}&width={1}&height={2}&constrain=true",
                                 imagePath, width, height);
        }

        private List<GalleryItem> GetGalleryItems()
        {
            //Get the media items from the Umbraco cache (which is only in the library class).
            XPathNodeIterator nodes = umbraco.library.GetMedia(folderId, true);

            //Convert the data to Xml.
            XDocument xmlDocument = XDocument.Parse(nodes.Current.InnerXml);

            //Convert the Xml to List<GallaryItem>.
            List<GalleryItem> gallaryItems =
                (
                    from gallaryItem in xmlDocument.Descendants("Image")
                    select new GalleryItem()
                    {
                        Name = gallaryItem.Attribute("nodeName").Value,
                        Path = gallaryItem.Element("umbracoFile").Value,
                    }
                ).ToList();

            return gallaryItems;
        }
    }
}